/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved.
 * secGear is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

//! Arm CCA plugin
//!
//! Call the hardware sdk or driver to get the specific evidence

use anyhow::*;
use base64_url;
use log;
use serde_json;
use super::tsm_report::*;

use crate::EvidenceRequest;

const MAX_CHALLENGE_LEN: usize = 64;

#[derive(Debug, Default)]
pub struct ArmccaAttester {}

impl ArmccaAttester {
    pub async fn tee_get_evidence(&self, user_data: EvidenceRequest) -> Result<String> {
        let challenge = base64_url::decode(&user_data.challenge)?;
        let len = challenge.len();
        if len <= 0 || len > MAX_CHALLENGE_LEN {
            log::error!(
                "challenge len is error, expecting 0 < len <= {}, got {}",
                MAX_CHALLENGE_LEN,
                len
            );
            bail!(
                "challenge len is error, expecting 0 < len <= {}, got {}",
                MAX_CHALLENGE_LEN,
                len
            );
        }

        let tsm = TsmReportPath::new(TsmReportProvider::Cca)?;
        let token = tsm.attestation_report(TsmReportData::Cca(challenge))?;
        let ev =
            serde_json::to_string(&token).context("Serialization of CCA evidence failed")?;
        Ok(ev)
    }
}

pub fn detect_platform() -> bool {
    //#[cfg(target_arch = "aarch64")]
    return TsmReportPath::new(TsmReportProvider::Cca).is_ok();
    //#[cfg(not(target_arch = "aarch64"))]
    //return false;
}
